
import 'dart:async';
import 'dart:math';

import 'package:flutter/material.dart';
import 'package:qx_global_ads/src/ad_item_logic.dart';
import 'package:qx_global_ads/src/response.dart';
import 'package:url_launcher/url_launcher.dart';

class GameRecommendWidget extends StatefulWidget {
    final double size; // 游戏图标大小
    final double leftOffset; // 左边的距离
    final double positionY; // 0-1 之间的相对位置
    final String platform; // 渠道名
    final String packageName;
    final double borderRadius; // 圆角大小
    final bool isDebug; // 是否是调试模式
    const GameRecommendWidget({
      super.key,
      this.size = 41.0,
      this.leftOffset = 9.0,
      this.positionY = 0.5,
      this.platform = "xiaomi",
      this.packageName = "com.example.example",
      this.borderRadius = 7,
      this.isDebug = false
    });

    @override
    State<GameRecommendWidget> createState() => _GameRecommendWidgetState();
}

class _GameRecommendWidgetState extends State<GameRecommendWidget> with TickerProviderStateMixin {

  Timer? switchTimer;
  late AnimationController _animationController;
  late Animation<double> _shakeAnimation;
  bool isShow = false;
  AdItem? curAd;
  


  @override
  void initState() {
    super.initState();
     
     AdItemLogic.setDebug(widget.isDebug);
     AdItemLogic.setPackageName(widget.packageName);
     AdItemLogic.setPlatform(widget.platform);

    _fetchGames();
    _initShakeAnimation();
  }

   @override
  void dispose() {
    switchTimer?.cancel();
    _animationController.dispose();
    super.dispose();
  }

    // **初始化摇晃动画**
void _initShakeAnimation({double maxAngle = 30}) {
  _animationController = AnimationController(
    vsync: this,
    duration: const Duration(milliseconds: 800),
  );

  // 角度转换为弧度
  double maxRadians = maxAngle * (3.14159265 / 180);

  _shakeAnimation = TweenSequence<double>([
    TweenSequenceItem(tween: Tween(begin: -maxRadians, end: maxRadians), weight: 1),
    TweenSequenceItem(tween: Tween(begin: maxRadians, end: -maxRadians), weight: 1),
    TweenSequenceItem(tween: Tween(begin: -maxRadians * 0.7, end: maxRadians * 0.7), weight: 1),
    TweenSequenceItem(tween: Tween(begin: maxRadians * 0.7, end: -maxRadians * 0.7), weight: 1),
    TweenSequenceItem(tween: Tween(begin: -maxRadians * 0.5, end: maxRadians * 0.5), weight: 1),
    TweenSequenceItem(tween: Tween(begin: maxRadians * 0.5, end: -maxRadians * 0.5), weight: 1),
    TweenSequenceItem(tween: Tween(begin: -maxRadians * 0.3, end: maxRadians * 0.3), weight: 1),
    TweenSequenceItem(tween: Tween(begin: maxRadians * 0.3, end: 0), weight: 1), // 最后回归 0
  ]).animate(CurvedAnimation(
    parent: _animationController,
    curve: Curves.easeOut,
  ));

}
    // **请求游戏列表**
  Future<void> _fetchGames() async {
    await AdItemLogic.fetchAds();
    await waitToStart();
  }


  Future<void> waitToStart() async {
     var ad = AdItemLogic.ad;
     if(ad != null){
       var delayStart =  ad.firstInterval ?? 0;
       if(delayStart != 0 && ad.items?.isEmpty == false ){
          await Future.delayed(Duration(seconds: delayStart));
          setState(() {
             isShow = true;
          });
          _startGameRotation();
       }
     }
  }




   // **定时切换游戏**
  void _startGameRotation() {
    setState(() {
        curAd = AdItemLogic.getAd();
    });
    _animationController.reset();
    _animationController.forward(); // 触发摇
    var ad = AdItemLogic.ad;
    if(ad != null){
      switchTimer = Timer.periodic(Duration(seconds: (ad.duration ?? 0) + (Random().nextInt(21))), (timer) {
          AdItemLogic.adComplete();
          AdItemLogic.addAdIndex();
          setState(() { 
            curAd = AdItemLogic.getAd();
          });
          _animationController.reset();
          _animationController.forward(); // 触发摇晃动画
        });
      }
    }
  
    @override
  Widget build(BuildContext context) {
    // **未加载完成或加载失败时，不占位**
    if (!isShow) {
      return const SizedBox.shrink();
    }
    return Positioned(
      left: widget.leftOffset,
      top: MediaQuery.of(context).size.height * widget.positionY - widget.size * 0.5,
      child: AnimatedBuilder(
        animation: _animationController,
        builder: (context, child) {
          return Transform.rotate(
            angle: isShow? _shakeAnimation.value:0,
            child: child,
          );
        },
        child: Stack(
          clipBehavior: Clip.none,
          children: [
            // 游戏图标
            ClipRRect(
              borderRadius: BorderRadius.circular(widget.borderRadius),
              child: GestureDetector(
                onTap: () async {  
                   await launchUrl(Uri.parse(curAd?.url ?? ""));
                   AdItemLogic.adClick();
                },
                child: Image.network(
                  curAd?.icon ?? "",
                  width: widget.size,
                  height: widget.size,
                  fit: BoxFit.cover,
                ),
              ),
            ),
           // 关闭按钮
            Positioned(
              top: -widget.size * 0.15,
              right: -widget.size * 0.15,
              child: GestureDetector(
                behavior: HitTestBehavior.translucent, // 扩大点击区域
                onTap: () async {
                  switchTimer?.cancel();
                  setState(() {
                    isShow = false;
                  });  
                  if (await AdItemLogic.adClose()) {
                    await waitToStart();
                  }
                },
                child: Container(
                  width: widget.size * 0.6, // 加大整个点击区域
                  height: widget.size * 0.6,
                  alignment: Alignment.center, // 图标居中显示
                  child: Container(
                    width: widget.size * 0.3, // 视觉上不变
                    height: widget.size * 0.3,
                    decoration: const BoxDecoration(
                      shape: BoxShape.circle,
                      color: Colors.red,
                    ),
                    alignment: Alignment.center,
                    child: Icon(
                      Icons.close,
                      size: widget.size * 0.3 * 0.6,
                      color: Colors.white,
                    ),
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }





}